using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Provider.Consul;
using Ocelot.Provider.Polly;

using OcelotGatewayProj;
using System;
using System.IO;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddJsonFile(Path.Combine(AppContext.BaseDirectory, "ocelot.json"));
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddCors(policy =>
{
    policy.AddPolicy("CorsPolicy", opt => opt
        .AllowAnyOrigin()
        .AllowAnyHeader()
        .AllowAnyMethod()
        .WithExposedHeaders("X-Pagination", "Content-Disposition")
    );
});
builder.Services
    .AddOcelot()
    .AddConsul()
    .AddPolly();


ushort? port = builder.Configuration.GetSection("HttpPort").Get<ushort?>();
ushort? httpsPort = builder.Configuration.GetSection("HttpsPort").Get<ushort?>();
string host = builder.Configuration.GetSection("Host").Get<string>();
HttpsLocalConf httpsConf = builder.Configuration.GetSection(nameof(HttpsLocalConf)).Get<HttpsLocalConf>();

// if (httpsPort > 0) builder.Services.AddHttpsRedirection(conf => { conf.HttpsPort = httpsPort; });

builder.WebHost.ConfigureKestrel(op =>
{
    op.ListenAnyIP(port ?? 9500);
    if (httpsPort > 0)
    {
        if (httpsConf != null && !string.IsNullOrEmpty(httpsConf.Passwd) && File.Exists(httpsConf.File))
        {
            Action<ListenOptions> confAction = listenOptions => { listenOptions.UseHttps(httpsConf.File, httpsConf.Passwd); };
            op.ListenAnyIP(httpsPort.Value, confAction);
        }
        else
        {
            op.ListenAnyIP(httpsPort.Value);
        }
    }
});

var app = builder.Build();

//app.UseHttpsRedirection();

app.UseCors("CorsPolicy");
app.UseWebSockets();
app.UseOcelot().Wait();
app.MapControllers();
app.Run();
